<?php

/**
 * UserModel.php 注释
 * 
 * @package 
 * @subpackage 
 * 
 */
class UserModel{
	/**
	 * 数据库对象
	 *
	 * @var Mysql
	 */
	private $db;
	
	/**
	 * 构造方法
	 *
	 * @param Mysql $db
	 */
	public function __construct($db)
	{
		$this->db = $db;
	}
	
	/**
	 * 添加
	 */
	public function add( array $value )
	{
		$v = array();
//		$v["uid"] = (int)$value["uid"];
		$v["username"] = $value["username"];
		$v["password"] = $value["password"];
		$v["cash"] = (int)$value["cash"];
		$v["RegIp"] = $value["RegIp"];
		$v["RegTime"] = $value["RegTime"];
		
		return $this->db->insert("user", $v, true);
	}
	
	/**
	 * 修改
	 */
	public function change($uid, array $value)
	{
		$v = array();
		isset($value["username"]) && $v["username"] = $value["username"];
		isset($value["password"]) && $v["password"] = $value["password"];
		isset($value["cash"]) && $v["cash"] = (int)$value["cash"];

		$this->db->update("user", $v, 'uid=' . (int)$uid);
	}
	
	/**
	 * 删除
	 */
	public function del($uid)
	{
		$this->db->delete("user", 'uid=' .  (int)$uid);
	}
	
	/**
	 * 读取列表
	 *
	 * @param Integer $nowp
	 * @param Integer $per_page
	 */
	public function fetchAll($nowp, $per_page)
	{
		$where = '';		
		$totalNum = $this->db->fetchOne ('select count(*) from user ' . $where);
        
        require_once APP . '/application/models/Util.php';
        
        $pageInfo = Util::page ($totalNum, $per_page, $nowp);
        $start    = $pageInfo ['start'];
        $list     = $this->db->fetchAll ('select * from user' . $where .' order by uid desc limit ' . $start . ',' . $per_page);
        
        return Array ('page' => $pageInfo['page'], 'list' => $list);
	}
	
	/**
	 * 读取投注记录
	 *
	 * @param Integer $nowp
	 * @param Integer $per_page
	 */
	public function fetchLogAll($nowp, $per_page)
	{
		$where = '';		
		$totalNum = $this->db->fetchOne ('select count(*) from betlog ' . $where);
        
        require_once APP . '/application/models/Util.php';
        
        $pageInfo = Util::page ($totalNum, $per_page, $nowp);
        $start    = $pageInfo ['start'];
        $list     = $this->db->fetchAll ('select t1.*,t2.username from betlog t1 
        left join user t2 on t2.uid=t1.uid ' . $where .' order by id desc limit ' . $start . ',' . $per_page);
        
        return Array ('page' => $pageInfo['page'], 'list' => $list);
	}
	
	/**
	 * 显示
	 */
	public function show($uid)
	{
		return $this->db->fetchRow("select * from `user` where uid=\"?\"", array($uid));
	}
	
	
	/**
	 * 显示
	 */
	public function isUsernameExists($username)
	{
		return $this->db->fetchOne("select count(*) from `user` where username=\"?\"", array($username));
	}
}